package com.irssproject.app.dao.lectorRSS.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.irssproject.app.dao.lectorRSS.iface.FeedsDAO;
import com.irssproject.app.entitats.Feed;

public class FeedsDAOHibernate extends HibernateDaoSupport implements FeedsDAO {

    @Override
    public Long insertFeed(String feedTitle, String feedLink) {
        return (Long)getHibernateTemplate().save(new Feed(feedTitle, feedLink));
    }

    @Override
    public Feed getFeed(String urlFeed) {
        List<Feed> feedLst = (List<Feed>) getHibernateTemplate().find("from Feed where link = ?", urlFeed);
        return feedLst!=null && feedLst.size()==1 ? feedLst.get(0) : null;
    }

    public void deleteFeed(Feed feed) {

        getHibernateTemplate().delete(feed);
    }

    @SuppressWarnings("unchecked")
    public Feed getFeedByLink(Feed feed) {
        List<Feed> listFeed = (List<Feed>) getHibernateTemplate().find("from Feed where link = ?", feed.getLink());

        if (listFeed.size() > 0) {
            return listFeed.get(0);
        } else {
            return null;
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Feed> getLlistaFeeds(String likeNom) {

        try {
            DetachedCriteria criteria = DetachedCriteria.forClass(Feed.class);
            criteria.add(Restrictions.like("titol", "%" + likeNom + "%"));
            List<Feed> li = getHibernateTemplate().findByCriteria(criteria);
            return li;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Feed> getListFeeds() {
        return (List<Feed>) getHibernateTemplate().loadAll(Feed.class);
    }
}
